import React, { useEffect, useState } from 'react';
import {
  Card,
  Row,
  Col,
  TreeSelect,
  DatePicker,
  Table,
  Statistic,
  message,
  Form,
  Button,
} from 'antd';
import {
  exportIntelligentCallStatistics,
  getCasOrganizationsShow,
  getIntelligentCallStatistics,
} from 'admin/servers/modules/Cas';
import type { ColumnsType } from 'antd/es/table';
import type { IntelligentCallStatisticsItem, OrganizationItem } from 'admin/schema/Cas';
import moment from 'moment';
import { convertToTree } from '../utils';
import { map, multiply } from 'lodash';

const { RangePicker } = DatePicker;

const IntelligentCall: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [organizations, setOrganizations] = useState<
    Omit<OrganizationItem, 'children' | 'description'>[]
  >([]);
  const [form] = Form.useForm();
  const [overview, setOverview] = useState<IntelligentCallStatisticsItem>();
  const [dataList, setDataList] = useState<IntelligentCallStatisticsItem[]>([]);

  const handleReset = () => {
    form.setFieldsValue({
      organization: map(organizations, 'id'),
      dateRange: [moment().subtract(7, 'days'), moment()],
    });
    getIntelligentCallStatistics({
      orgId: map(organizations, 'id'),
      startDate: moment().subtract(7, 'days').format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
    }).then(res => {
      if (res.status === '200') {
        setOverview(res.data.overview);
        setDataList([...res.data.dataList, res.data.subtotal]);
      }
    });
  };

  const handleFinish = (values: any) => {
    getIntelligentCallStatistics({
      orgId: values.organization,
      startDate: values.dateRange[0].format('YYYY-MM-DD'),
      endDate: values.dateRange[1].format('YYYY-MM-DD'),
    }).then(res => {
      if (res.status === '200') {
        setOverview(res.data.overview);
        setDataList([...res.data.dataList, res.data.subtotal]);
      }
    });
  };

  const handleExport = () => {
    const { organization, dateRange } = form.getFieldsValue();
    const startDate = dateRange[0].format('YYYY-MM-DD');
    const endDate = dateRange[1].format('YYYY-MM-DD');
    const fileName = `智能外呼统计_${startDate}_${endDate}.xlsx`;

    exportIntelligentCallStatistics({
      orgId: organization,
      startDate: startDate,
      endDate: endDate,
    })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
        message.success('导出成功');
      })
      .catch(error => {
        console.error('导出失败:', error);
        message.error('导出失败，请稍后重试');
      });
  };

  useEffect(() => {
    getCasOrganizationsShow()
      .then(res => {
        if (res.status === 200) {
          setOrganizations(res.data);
          form.setFieldsValue({
            organization: map(res.data, 'id'),
            dateRange: [moment().subtract(7, 'days'), moment()],
          });
          return getIntelligentCallStatistics({
            orgId: map(res.data, 'id'),
            startDate: moment().subtract(7, 'days').format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
          });
        }
      })
      .then(res => {
        if (res.status === '200') {
          setOverview(res.data.overview);
          setDataList([...res.data.dataList, res.data.subtotal]);
        }
      })
      .finally(() => {
        setLoading(false);
      });
    // eslint-disable-next-line
  }, []);

  const columns: ColumnsType<IntelligentCallStatisticsItem> = [
    {
      title: '日期',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '呼叫量',
      dataIndex: 'callVolume',
      key: 'callVolume',
      sorter: (a, b) => a.callVolume - b.callVolume,
    },
    {
      title: '接通量',
      dataIndex: 'connectedVolume',
      key: 'connectedVolume',
      sorter: (a, b) => a.connectedVolume - b.connectedVolume,
    },
    {
      title: '接通率',
      dataIndex: 'connectionRate',
      key: 'connectionRate',
      render: text => {
        return <span>{multiply(text, 100).toFixed(2)}%</span>;
      },
      sorter: (a, b) => Number(a.connectionRate) - Number(b.connectionRate),
    },
    {
      title: '总通话时长',
      dataIndex: 'totalCallDuration',
      key: 'totalCallDuration',
      sorter: (a, b) => a.totalCallDuration - b.totalCallDuration,
    },
    {
      title: '平均通话时长',
      dataIndex: 'averageCallDuration',
      key: 'averageCallDuration',
      sorter: (a, b) => a.averageCallDuration - b.averageCallDuration,
    },
  ];

  return (
    <div>
      <Card>
        <Form form={form} layout="inline" onFinish={handleFinish} style={{ marginBottom: 16 }}>
          <Form.Item label="单位" name="organization">
            <TreeSelect
              treeData={convertToTree(organizations)}
              maxTagCount={1}
              placeholder="请选择单位"
              showCheckedStrategy={TreeSelect.SHOW_ALL}
              treeCheckable
              allowClear
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              style={{ width: 300 }}
            />
          </Form.Item>
          <Form.Item label="日期" name="dateRange">
            <RangePicker style={{ width: 300 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>

        {overview && (
          <Card title="智能外呼数据概览" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={4}>
                <Statistic
                  title="接通率"
                  value={multiply(Number(overview.connectionRate), 100).toFixed(2)}
                  suffix="%"
                />
              </Col>
              <Col span={4}>
                <Statistic title="呼叫量" value={overview.callVolume} />
              </Col>
              <Col span={4}>
                <Statistic title="接通量" value={overview.connectedVolume} />
              </Col>
              <Col span={4}>
                <Statistic title="总通话时长" value={overview.totalCallDuration} />
              </Col>
              <Col span={4}>
                <Statistic title="平均通话时长" value={overview.averageCallDuration} />
              </Col>
            </Row>
          </Card>
        )}

        <Card
          title="智能外呼数据详情"
          extra={
            <Button type="primary" onClick={handleExport}>
              导出
            </Button>
          }
        >
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey="time"
            loading={loading}
            pagination={false}
          />
        </Card>
      </Card>
    </div>
  );
};

export default IntelligentCall;
